package de.bazinga.rotw.vehicle;

import com.captiveimagination.jgn.message.Message;
import com.captiveimagination.jgn.message.type.CertifiedMessage;
import com.captiveimagination.jgn.message.type.PlayerMessage;
import com.captiveimagination.jgn.message.type.TimestampedMessage;
import com.jme.math.Vector3f;

import de.bazinga.rotw.collision.CollidableObjects;
import de.bazinga.rotw.game.RotwGameState;
import de.bazinga.rotw.network.Server;
import de.bazinga.rotw.network.message.GameMessage;

public class VehicleDamageMessage extends Message implements CertifiedMessage, PlayerMessage, TimestampedMessage, GameMessage {

	boolean requestInformation = false;
	private int damage = 0;
	private int vehicleIndex = 0;
	private Vector3f location = null;
	
	public void setDamage(int damage) {
		this.damage = damage;
	}

	public int getDamage() {
		return damage;
	}

	public void setVehicleIndex(int vehicleIndex) {
		this.vehicleIndex = vehicleIndex;
	}

	public int getVehicleIndex() {
		return vehicleIndex;
	}

	public void setLocation(Vector3f location) {
		this.location = location;
	}

	public Vector3f getLocation() {
		return location;
	}

	public boolean isRequestInformation() {
		return requestInformation;
	}

	public void setRequestInformation(boolean requestInformation) {
		this.requestInformation = requestInformation;
	}
	
	public void handleMessage(RotwGameState game, Message msg, boolean server) {
		if(!(msg instanceof VehicleDamageMessage)) return ;

		// Player touched a item
		VehicleDamageMessage vdm = (VehicleDamageMessage)msg;
		
		if(server) {
        	Vehicle veh = (Vehicle)CollidableObjects.getInstance().getObjects("vehicle").get(
					vdm.getVehicleIndex());
        	
        	if(vdm.isRequestInformation()) {
        		
        		VehicleDamageMessage vdmInfo = new VehicleDamageMessage();
        		vdmInfo.setVehicleIndex(vdm.getVehicleIndex());
        		vdmInfo.setDamage(veh.getDamage());
        		vdmInfo.setLocation(veh.getLocalTranslation());
        		
        		((Server)game.getSyncManager()).getServer().sendToPlayer(vdmInfo, vdm.getPlayerId());
        	}else{
				veh.setDamage(vdm.getDamage(), false);
	        	
	
	        	if(vdm.getLocation() != null) {
	        		veh.setLocalTranslation(vdm.getLocation());
	        	}
	        	
	        	// Send to Clients
	        	((Server)game.getSyncManager()).getServer().sendToAllExcept(vdm, vdm.getPlayerId());
        	}
		}else{
			Vehicle veh = (Vehicle)CollidableObjects.getInstance().getObjects("vehicle").get(
					vdm.getVehicleIndex());
        	veh.setDamage(vdm.getDamage(), false);
        	
        	if(vdm.getLocation() != null) {
        		veh.setLocalTranslation(vdm.getLocation());
        	}
		}
	}
}